package com.orangelife.mobile.pay.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.jump.PropertyJumper;
import com.common.jump.WebJumper;
import com.common.sp.PaySp;
import com.common.util.CommonHttpBiz;
import com.common.util.OrangePhoneUtil;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.StringUtil;
import com.curry.orangelife.mobile.R;
import com.datatrack.DataTrack;
import com.orangelife.mobile.app.application.CurryApplication;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.confirmOrder.biz.OrderType;
import com.orangelife.mobile.goodsrent.dao.GoodsDao;
import com.orangelife.mobile.hourlyEmployee.activity.OrderDetailActivity;
import com.orangelife.mobile.individual.activity.BalanceDetailActivity;
import com.orangelife.mobile.goodsOrder.activity.MyGoodsOrderListActivity;
import com.orangelife.mobile.main.biz.JumpUtil;
import com.orangelife.mobile.pay.biz.PayResultHttpBiz;
import com.orangelife.mobile.pay.biz.PaymentModule;
import com.orangelife.mobile.lookRepair.activity.GrapSingle2Activity;
import com.orangelife.mobile.lookRepair.activity.LookForRepairDetailActivity;
import com.orangelife.mobile.main.activity.ServiceOrderActivity;
import com.orangelife.mobile.parkingcard.activity.HaveCardListActivity;
import com.orangelife.mobile.pay.view.PayPwdSetTipDialog;
import com.orangelife.mobile.shoppingcart.activity.ShoppingCartActivity;
import com.orangelife.mobile.shoppingcart.biz.ShoppingCartBiz;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


/**
 * @author Administrator
 *         支付结果页面
 */
public class PaidResultActivity extends OrangeLifeBaseActivity
        implements OnClickListener {
    private Button btnPaidLeft;
    private Button btnPaidRight;
    private TextView tvTitle, tvInfo, tvPhone, tvOrderInfoText,
            tvOrderTotalPrice, tvValidityDateValue;
    /** 支付获得的橙汁（积分） */
    private TextView tvJifen;
    private LinearLayout llReturn;
    private ImageView ivIcon;
    private RelativeLayout rlValidityDate;
    private View viewValidityDate;

    private boolean isShopping;
    private String orderID;
    /** 用于查询可用支付方式的参数，和订单类型相对应 */
    private String orderTypeForPay;
    private String totalPrice = "";
    private String lotteryUrl;
    private ViewGroup content;

    /** Activit 名称 **/
    private final String MODULE_NAME = "/payOdr/payResult";
    private String mOrderType;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paid_result);
        isShopping = ((CurryApplication) this.getApplicationContext()).getShopping();
        initView();
        getIntentInfo();
        setListener();
        setTitle();
        DataTrack.browseTrack(DataTrack.APP_NAME, MODULE_NAME, null);
        requestHasLottery();
        validatePayPwdStatus();
    }

    private void getIntentInfo() {
        orderID = getIntent().getStringExtra("orderID");
        orderTypeForPay = getIntent().getStringExtra(PaymentModule.PAID_METHOD);
        totalPrice = getIntent().getStringExtra("totalPrice");
        mOrderType = getIntent().getStringExtra("orderType");
        String orderInfo = getIntent().getStringExtra("orderInfo");
        String point = getIntent().getStringExtra("points");
        String info = getIntent().getStringExtra("info");
        String btnText = getIntent().getStringExtra("btnText");
        boolean isSuccess = getIntent().getBooleanExtra("isSuccess", true);
        boolean isPaying = getIntent().getBooleanExtra("isPaiding", true);

        setBtnText(btnText, isSuccess);
        setIcon(isSuccess, isPaying);
        setInfo(info, orderInfo, totalPrice);
        showPoint(point);
        showParkingCardInfo(isSuccess);
    }

    private void validatePayPwdStatus() {
        if (!PaySp.isNeverSetPayPwd()) {
            PayPwdSetTipDialog ppsd = new PayPwdSetTipDialog(this);
            ppsd.show();
        }
    }

    private void setTitle() {
        tvTitle.setText(getResources().getString(R.string.paid_result));
    }

    private void setBtnText(String btnText, boolean isSuccess) {
        if (!isSuccess) {/* 支付失败 */
            btnPaidLeft.setText(getString(R.string.paid_again));
            btnPaidRight.setText(getString(R.string.close));/*默认是""*/
        } else {
            if (!StringUtil.isBlank(btnText)) {
                btnPaidRight.setText(btnText);
            }
            if (PaymentModule.mode[9].equals(orderTypeForPay)) {/* 钱包余额充值 */
                showSingleButton();
            } else if (OrderType.PROPERTY_WALLET_RECHARGE.equals(mOrderType)) {/*物业缴费钱包充值*/
                btnPaidLeft.setText("缴纳物业费");
            }
        }
    }

    /** 只显示一个按钮 */
    private void showSingleButton() {
        btnPaidLeft.setVisibility(View.GONE);
        ViewGroup.LayoutParams params = btnPaidRight.getLayoutParams();
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        btnPaidRight.setLayoutParams(params);
    }

    private void setIcon(boolean isSuccess, boolean isPaying) {
        if (!isSuccess) {/*失败*/
            ivIcon.setBackgroundResource(R.drawable.exclamation);
        }
        if (!isPaying) {/*支付中*/
            ivIcon.setBackgroundResource(R.drawable.paiding);
        }
    }

    private void setInfo(String info, String orderInfo, String totalPrice) {
        if (!StringUtil.isBlank(info)) {/*默认显示支付成功*/
            tvInfo.setText(info);
        }
        tvOrderInfoText.setText(orderInfo);
        tvOrderTotalPrice.setText(totalPrice);
    }

    private void showPoint(String point) {/*橙汁（积分）默认不显示*/
        if (!StringUtil.isBlank(point) && !PaymentModule.mode[4].equals(orderTypeForPay)) {//其实不传不显示就行了，没必要判断类型（类型也不能改，改动必然会改代码，除非服务器控制是否显示橙汁）
            tvJifen.setVisibility(View.VISIBLE);
            tvJifen.setText("交易成功后，获得" + point + "ml橙汁!");
        }
    }

    private void showParkingCardInfo(boolean isSuccess) {
        if (isSuccess && PaymentModule.mode[5].equals(orderTypeForPay)) {/* 支付成功&是停车卡*/
            rlValidityDate.setVisibility(View.VISIBLE);
            viewValidityDate.setVisibility(View.VISIBLE);
            tvValidityDateValue.setText(CurryApplication.getInstance().getValidity());
        }
    }

    private void onClickLeftButton() {
        dataTrackClick("btnViewOdr", null);

        if (!getIntent().getBooleanExtra("isSuccess", true)) {/* 支付失败 */
            finish();
        } else {/* 支付成功 */
            finishPaidActivity();
            finishFailActivity();
            int feeType = getIntent().getIntExtra("feeType", 3);
            if (feeType == 2) {/* 维修下单 */
                Intent intent = new Intent(PaidResultActivity.this,
                        GrapSingle2Activity.class);
                intent.putExtra("followID",
                        getIntent().getStringExtra("repairID"));
                startActivity(intent);
            } else if (feeType == 0) {/*估价单*/
                Intent intent = new Intent(PaidResultActivity.this,
                        LookForRepairDetailActivity.class);
                intent.putExtra("jumpuri", "null");
                startActivity(intent);
            } else if (feeType == 1) {/*定价单*/
                Intent intent = new Intent(PaidResultActivity.this,
                        LookForRepairDetailActivity.class);
                intent.putExtra("jumpuri", "null");
                startActivity(intent);
            } else {
                if (OrderType.PROPERTY_WALLET_RECHARGE.equals(mOrderType)) {/*物业缴费钱包充值订单*/
                    jumpToPropertyBill();
                } else if (PaymentModule.mode[4].equals(orderTypeForPay)) {/*物业缴费历史记录*/
                    jumpToPropertyHistory();
                } else if (PaymentModule.mode[0].equals(orderTypeForPay) || PaymentModule.mode[2].equals(orderTypeForPay)) {/* 餐桌，团购，积分商品 */
                    Intent intent = new Intent(PaidResultActivity.this, MyGoodsOrderListActivity.class);
                    startActivity(intent);
                } else if (PaymentModule.mode[8].equals(orderTypeForPay)) {/* 钟点工 */
                    Intent intent = new Intent(PaidResultActivity.this,
                            OrderDetailActivity.class);
                    intent.putExtra("jumpuri",
                            getIntent().getStringExtra("serviceOrderID"));
                    startActivity(intent);
                } else if (PaymentModule.mode[5].equals(orderTypeForPay)) {/*停车卡*/
                    finish();
                } else if (PaymentModule.mode[9].equals(orderTypeForPay)) {/*钱包余额充值*/
                    Intent intent = new Intent(PaidResultActivity.this,
                            BalanceDetailActivity.class);
                    startActivity(intent);
                } else if (PaymentModule.mode[1].equals(orderTypeForPay)) {
                    if (isShopping) {/*删除购物车中已购买的商品*/
                        ShoppingCartBiz.delGoodsList(getIntent().getStringArrayListExtra("productsID"));
                    }
                    Intent intent = new Intent(PaidResultActivity.this, MyGoodsOrderListActivity.class);
                    startActivity(intent);
                } else if (PaymentModule.mode[10].equals(orderTypeForPay)) {
                    if (isShopping) {
                        GoodsDao.getInstance().deleteAllGoodsInfo();
                    }
                    IntentHelper.getInstances().intentWithExtraString(PaidResultActivity.this, ServiceOrderActivity.class, "location", 3);
                } else if (PaymentModule.mode[11].equals(orderTypeForPay)) {
                    IntentHelper.getInstances().intentWithExtraString(PaidResultActivity.this, ServiceOrderActivity.class, "location", 4);
                } else if (PaymentModule.COMMUNITY_ACTIVITY.equals(orderTypeForPay)) {
                    WebJumper.jumpToCommunityActivityOrderDetail(this, orderID);
                }
            }
        }
    }

    private void onClickRightButton() {
        ExitApplication.getInstance().addPaidActivity(
                PaidResultActivity.this);
        finishPaidActivity();
        if (PaymentModule.mode[5].equals(orderTypeForPay)) {
            Intent intent = new Intent(PaidResultActivity.this,
                    HaveCardListActivity.class);
            startActivity(intent);
        } else if (PaymentModule.mode[9].equals(orderTypeForPay)) {/*钱包余额充值*/
            finishFailActivity();
            Intent intent = new Intent(PaidResultActivity.this,
                    BalanceDetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("walletID", CurryApplication.getInstance().getWalletID());
            intent.putExtras(bundle);
            startActivity(intent);
        } else if (PaymentModule.mode[1].equals(orderTypeForPay)) {/*周边乐购*/
            if (isShopping) {
                ShoppingCartBiz.delGoodsList(getIntent().getStringArrayListExtra("productsID"));
                finishFailActivity();
                IntentHelper.getInstances().getIntent(this, ShoppingCartActivity.class);
            }
        } else if (PaymentModule.mode[10].equals(orderTypeForPay)) {/*物品租借*/
            if (isShopping) {
                GoodsDao.getInstance().deleteAllGoodsInfo();
            }
        }
        dataTrackClick("btnCpl", null);
    }

    private void jumpToPropertyBill() {
        PropertyJumper.jumpToPropertyFeeList(this);
    }

    private void jumpToPropertyHistory() {
        PropertyJumper.jumpToPropertyHistoryList(this);
    }

    private void callServiceTel() {
        OrangePhoneUtil.callCustomerService2(PaidResultActivity.this);
    }

    private void requestHasLottery() {/*是否抽奖*/
        showDialog();
        PayResultHttpBiz.getHasLottery(mOrderType, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                closeDialog();
                Map<String, Object> entity = CommonHttpBiz.handleEntity(jsonObject);
                if (entity != null) {
                    String isLottery = String.valueOf(entity.get("islottery"));/*0：没有 1：有*/
                    lotteryUrl = String.valueOf(entity.get("lotteryUrl"));/*抽奖活动路径*/
                    if ("1".equals(isLottery)) {
                        showLotteryView();
                    }
                }
            }
        });
    }

    private void showLotteryView() {/*显示中奖页面*/
        content = (ViewGroup) this.findViewById(android.R.id.content);
        final LinearLayout container = new LinearLayout(this);
        container.setGravity(Gravity.BOTTOM);
        container.setOrientation(LinearLayout.HORIZONTAL);
        container.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        View view = LayoutInflater.from(this).inflate(R.layout.v_lottery, null);
        Button btnClick = (Button) view.findViewById(R.id.btnClick);
        ImageView ivClose = (ImageView) view.findViewById(R.id.ivClose);
        TextView tvOkInfo = (TextView) view.findViewById(R.id.tvOkInfo);
        String info = "<span align=\"center\">充值成功！</span><br><span>恭喜您获得<font color=\"#FEEF35\"> <big><b>1</b></big> </font>次抽奖机会</span>";
        tvOkInfo.setText(Html.fromHtml(info));
        ivClose.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                clearLotteryView(container);
            }
        });
        btnClick.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpToLottery();
                clearLotteryView(container);
            }
        });
        LinearLayout.LayoutParams paramsFill = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        view.setLayoutParams(paramsFill);
        container.addView(view);
        content.addView(container);
    }

    private void clearLotteryView(View container) {/*清除中奖页面*/
        if (content != null) {
            content.removeView(container);
        }
    }

    private void jumpToLottery() {/*跳转到抽奖界面*/
        if (!StringUtil.isBlank(lotteryUrl)) {
            JumpUtil.jumpActivity(PaidResultActivity.this, ((CurryApplication) getApplication()).getServerURL() + lotteryUrl);
        }
    }

    private void finishPaidActivity() {
        ExitApplication.getInstance().addPaidActivity(
                PaidResultActivity.this);
        ExitApplication.getInstance().finishPaidActivity();
    }

    private void finishFailActivity() {
        ExitApplication.getInstance().finishFailActivity();
    }

    private void setListener() {
        btnPaidLeft.setOnClickListener(this);
        btnPaidRight.setOnClickListener(this);
        tvPhone.setOnClickListener(this);
    }

    private void initView() {
        viewValidityDate = findViewById(R.id.viewValidityDate);
        llReturn = (LinearLayout) findViewById(R.id.ib_title_left);
        rlValidityDate = (RelativeLayout) findViewById(R.id.rlValidityDate);
        ivIcon = (ImageView) findViewById(R.id.ivIcon);
        tvOrderInfoText = (TextView) findViewById(R.id.tvOrderInfoText);
        tvOrderTotalPrice = (TextView) findViewById(R.id.tvOrderTotalPrice);
        tvValidityDateValue = (TextView) findViewById(R.id.tvValidityDateValue);
        tvInfo = (TextView) findViewById(R.id.tvInfo);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvPhone = (TextView) findViewById(R.id.tv_phone);
        tvJifen = (TextView) findViewById(R.id.tvJifen);//新增积分显示
        btnPaidRight = (Button) findViewById(R.id.btn_paid_home);
        btnPaidLeft = (Button) findViewById(R.id.btn_paid_detail);
        llReturn.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_paid_detail:
                onClickLeftButton();
                break;
            case R.id.btn_paid_home:
                onClickRightButton();
                break;
            case R.id.tv_phone:
                callServiceTel();
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ExitApplication.getInstance().finishPaidActivity();
    }

    /** 数据采集体不要删除 */
    public Map<String, Object> getDataTrack() {
        Map<String, Object> map = new HashMap<>();
        map.put("UI_HOST", DataTrack.APP_NAME);
        map.put("UI_PATH", MODULE_NAME);
        map.put("payResult", getIntent().getBooleanExtra("isSuccess", true) ? "成功" : "失败");
        return map;
    }
}
